<template>
  <div class="test-container">
    <h1 class="page-title">路由管理页面</h1>

    <div
      v-if="message"
      class="message"
      :class="{ success: isSuccess, error: !isSuccess }"
    >
      {{ message }}
    </div>

    <div v-if="isLoading" class="loading-container">
      <p>正在加载中...</p>
    </div>

    <div v-else-if="links.length > 0" class="links-container">
      <div class="title-row">
        <h2 class="section-title">已添加的路由</h2>
        <button
          @click="refreshLinks"
          class="refresh-button"
          :class="{ refreshing: isLoading }"
        >
          <span class="refresh-icon">↻</span>
          刷新
        </button>
      </div>
      <ul class="links-list">
        <li v-for="link in links" :key="link.id" class="link-item">
          <div class="link-row">
            <a :href="link.url" target="_blank" class="route-name">
              {{ link.link_name || '未命名路由' }}
            </a>
            <div class="action-buttons">
              <a :href="link.url" target="_blank" class="jump-button">跳转</a>
              <button @click="viewRouteUrl(link)" class="view-button">
                查看
              </button>
              <button @click="deleteLink(link.id)" class="delete-button">
                删除
              </button>
            </div>
          </div>
          <div v-if="link.showUrl" class="route-url-container">
            <div class="route-url">{{ link.url }}</div>
            <button @click="copyToClipboard(link.url)" class="copy-button">
              复制
            </button>
          </div>
        </li>
      </ul>
    </div>

    <div v-else class="empty-links">
      <p>暂无链接，请在添加页面进行添加</p>
      <button @click="refreshLinks" class="refresh-button">
        <span class="refresh-icon">↻</span>
        刷新
      </button>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  name: 'TestView',
  data() {
    return {
      links: [],
      message: '',
      isSuccess: false,
      isLoading: false,
    }
  },
  created() {
    // 页面加载时获取已有链接
    this.fetchLinks()
  },
  methods: {
    // 获取已添加的链接
    async fetchLinks() {
      try {
        this.isLoading = true
        const response = await request.get('/devices/test')

        // 处理不同的响应格式
        let linksData = []
        if (response.data) {
          if (Array.isArray(response.data)) {
            linksData = response.data
          } else if (response.data.data && Array.isArray(response.data.data)) {
            linksData = response.data.data
          } else if (
            response.data.links &&
            Array.isArray(response.data.links)
          ) {
            linksData = response.data.links
          }
        }

        // 初始化每个链接项的显示状态
        this.links = linksData.map((link) => ({
          ...link,
          showUrl: false,
        }))
      } catch (error) {
        console.error('获取链接失败:', error)
        this.message = error.message || '获取链接失败，请稍后重试'
        this.isSuccess = false

        // 如果是401错误，显示需要登录的提示
        if (error.response?.status === 401) {
          this.message = '此功能需要登录后使用'
          this.isSuccess = false
        }
      } finally {
        this.isLoading = false
      }
    },

    // 查看路由URL
    viewRouteUrl(link) {
      // 切换当前路由的显示状态
      link.showUrl = !link.showUrl
    },

    // 复制到剪贴板
    copyToClipboard(text) {
      navigator.clipboard
        .writeText(text)
        .then(() => {
          this.message = '已复制到剪贴板'
          this.isSuccess = true

          // 3秒后清除消息
          setTimeout(() => {
            if (this.message === '已复制到剪贴板') {
              this.message = ''
            }
          }, 3000)
        })
        .catch((err) => {
          console.error('复制失败:', err)
          this.message = '复制失败'
          this.isSuccess = false
        })
    },

    // 刷新链接列表
    refreshLinks() {
      this.message = ''
      this.fetchLinks()
    },

    // 删除链接
    async deleteLink(linkId) {
      // 二次确认
      if (!confirm('确定要删除这个路由吗？删除后无法恢复。')) {
        return
      }

      try {
        this.isLoading = true
        await request.delete(`/devices/test/${linkId}`)

        this.message = '链接删除成功'
        this.isSuccess = true

        // 重新获取链接列表
        await this.fetchLinks()
      } catch (error) {
        console.error('删除链接失败:', error)
        this.message = error.message || '删除链接失败，请稍后重试'
        this.isSuccess = false

        // 如果是401错误，显示需要登录的提示
        if (error.response?.status === 401) {
          this.message = '此功能需要登录后使用'
          this.isSuccess = false
        }
      } finally {
        this.isLoading = false
      }
    },
  },
}
</script>

<style scoped>
.test-container {
  max-width: 800px;
  width: 90%;
  margin: 20px auto;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  text-align: center;
}

.message {
  padding: 12px;
  margin-bottom: 15px;
  border-radius: 4px;
  font-size: 16px;
  text-align: center;
}

.success {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #e1f3d8;
}

.error {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
}

.links-container {
  margin-top: 20px;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 20px;
  margin: 0;
}

.refresh-button {
  background-color: #67c23a;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.refresh-button:hover {
  background-color: #85ce61;
}

.refresh-icon {
  margin-right: 5px;
  font-size: 16px;
  display: inline-block;
}

.refreshing .refresh-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-container {
  text-align: center;
  margin-top: 30px;
  color: #909399;
}

.empty-links {
  text-align: center;
  margin-top: 30px;
  color: #909399;
}

.empty-links p {
  margin-bottom: 15px;
}

.empty-links .refresh-button {
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
}

.links-list {
  list-style: none;
  padding: 0;
}

.link-item {
  padding: 15px 10px;
  border-bottom: 1px solid #f0f0f0;
}

.link-item:last-child {
  border-bottom: none;
}

.link-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: nowrap;
}

.route-name {
  max-width: 60vw;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  vertical-align: middle;
  color: #1a73e8;
  font-weight: bold;
  font-size: 18px;
  margin-right: 10px;
  transition: color 0.2s;
  text-decoration: none;
}

.route-name:hover {
  color: #0b57d0;
}

.action-buttons {
  display: flex;
  gap: 0;
}

.jump-button {
  margin-right: 6px;
  min-width: 60px;
  height: 36px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

.jump-button:hover {
  background-color: #388e3c;
}

.view-button {
  margin-right: 6px;
  min-width: 80px;
  height: 36px;
  background-color: #909399;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
}

.view-button:hover {
  background-color: #a6a9ad;
}

.delete-button {
  min-width: 60px;
  height: 36px;
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
}

.delete-button:hover {
  background-color: #f78989;
}

.route-url-container {
  display: flex;
  align-items: center;
  margin-top: 10px;
  padding: 8px;
  background-color: #f8f8f8;
  border-radius: 4px;
  border: 1px dashed #ddd;
}

.route-url {
  flex: 1;
  word-break: break-all;
  font-family: monospace;
  font-size: 14px;
  color: #606266;
  padding-right: 10px;
}

.copy-button {
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  cursor: pointer;
  font-size: 12px;
  white-space: nowrap;
}

.copy-button:hover {
  background-color: #66b1ff;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .test-container {
    width: 95%;
    padding: 15px;
  }

  .title-row {
    flex-direction: column;
    align-items: flex-start;
  }

  .section-title {
    margin-bottom: 10px;
  }

  .link-row {
    flex-direction: row;
    align-items: center;
  }

  .route-name {
    max-width: 50vw;
  }

  .action-buttons {
    align-self: auto;
    margin-left: auto;
  }

  .view-button,
  .delete-button {
    height: 30px;
    padding: 6px 8px;
  }

  .view-button:hover,
  .delete-button:hover {
    background-color: #e9e9e9;
    color: #409eff;
  }

  .route-url-container {
    flex-direction: column;
  }

  .route-url {
    margin-bottom: 10px;
    padding-right: 0;
  }

  .copy-button {
    width: 100%;
    padding: 8px;
  }

  .jump-button {
    height: 30px;
    padding: 6px 8px;
  }

  .jump-button:hover {
    background-color: #388e3c;
    color: #fff;
  }
}
</style>